﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using RLab.Visualization;
using RLab.Programming;
using System.Threading;

namespace rlab.presentation
{
    public partial class SceneForm : Form
    {
        private Renderer renderer;
        private PhysicScara s;
        private ScaraObserver observer;
        private PhysicEngine engine;
        
        public SceneForm()
        {
            InitializeComponent();
        }

        public void EvaluateText( string text )
        {
            logTxB.Clear();
            Interpeter.ExecuteAsync( text, s, observer );
        }

        internal bool InitializeGraphics()
        {
            try
            {
                renderer = new Renderer( renderPanel );
                engine = PhysicEngineModule.createEngine();

                s = ScaraModule.CreatePhysicScara( renderer, engine );

                observer = new ScaraObserver( logTxB );

                observer.Unsubscriber = ( s as IProgrammable ).TraceEvent.Subscribe( observer );

                return true;
            }
            catch
            {
                return false;
            }
        }

        internal void Render()
        {
            if ( renderer != null )
            {
                renderer.Render();
            }
            if ( engine != null )
            {
                Thread.Sleep( 2 );
                PhysicEngineModule.update( engine, 50F );
            }

            var v = s.Tool.End.GlobalPosition;

            Func<float, decimal> r = ( d ) => Math.Round( ( decimal )d, 0 );
            toolPosLbl.Text = string.Format( "X:{0} Y:{1} Z:{2}", r( v.X ), r( v.Y ), r( v.Z ) );
        }
        
        internal void DisposeScene()
        {
            observer.Dispose();
            ( s as IDisposable ).Dispose();
            engine.Scene.Dispose();
            engine.Core.Dispose();
            engine = null;
            ( renderer as IDisposable ).Dispose();
            renderer = null;
        }
    }
}
